package org.one.stone.soup.wiki.screen.multicaster;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Hashtable;
import org.one.stone.soup.screen.multicaster.ScreenMulticaster;
import org.one.stone.soup.screen.multicaster.ScreenMulticasterSessionListener;
import org.one.stone.soup.xml.XmlElement;
import org.one.stone.soup.xml.stream.XmlLoader;
public class MulticastRouter implements ScreenMulticasterSessionListener{
private int width;
private int height;
private static Hashtable sessions = new Hashtable();
public String startWebCast(Socket socket) {
try{
InputStream iStream = socket.getInputStream();
OutputStream oStream = socket.getOutputStream();
XmlElement header = XmlLoader.getStandardParser().parseElement(iStream);
if( sessions.get( header.getAttributeValueByName("id") )!=null )
{
socket.close();
return null;
}
iStream.read();
iStream.read();
width = iStream.read();
width = width << 8;
width += iStream.read();
height = iStream.read();
height = height << 8;
height += iStream.read();
int frameSize = width*height;
String sessionId = header.getAttributeValueByName("id");
ScreenMulticaster multicaster = new ScreenMulticaster(socket,frameSize,sessionId,this);
sessions.put( header.getAttributeValueByName("id"),multicaster );
return header.getAttributeValueByName("id");
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
}
public void play(Socket socket) {
try{
InputStream iStream = socket.getInputStream();
XmlElement header = XmlLoader.getStandardParser().parseElement(iStream);
String alias = header.getElementByName("alias").getValue();
play(header.getAttributeValueByName("id"),alias,socket);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void play(String id,String alias,Socket socket) {
try{
ScreenMulticaster multicaster = (ScreenMulticaster)sessions.get( id );
if(multicaster==null)
{
socket.close();
return;
}
OutputStream oStream = socket.getOutputStream();
oStream.write( (width & 0x0000FF00) >>>8 );
oStream.write( (width & 0x000000FF) );
oStream.write( (height & 0x0000FF00) >>>8 );
oStream.write( (height & 0x000000FF) );
oStream.flush();
multicaster.addClient( alias,socket );
}
catch(Exception e)
{
e.printStackTrace();
}
}
public boolean sessionExists(String id)
{
if(id==null)
{
return false;
}
if(sessions.get(id)!=null)
{
return true;
}
else
{
return false;
}
}
public void sessionClosed(String id, ScreenMulticaster session) {
sessions.remove( id );
}
}